package com.learn.springcloud.hystrixexplainindetailconsumer.exception.handle.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.client.RestTemplate;

import java.sql.SQLException;

/**
 * 异常捕获--注解方式
 * @Time : 2018/8/3 16:38
 * @Version : 1.0
 */
public class UserExceptionCatchAnnotationWay {

    private RestTemplate restTemplate;

    public UserExceptionCatchAnnotationWay(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @HystrixCommand(fallbackMethod = "sayHelloFallback")
    public String sayHello(String name) throws Exception {
        System.out.println("UserServiceException Running : " + name);
        String url = "http://hystrix-explain-in-detail-provider/request/command/say/hello?name={1}";

        if("aaa".equals(name)){
            throw new RuntimeException(name);
        }else if("bbbb".equals(name)){
            throw new SQLException(name);
        }

        return restTemplate.getForObject(url, String.class, name);
    }

    private String sayHelloFallback(String name, Throwable e){
        if("aaa".equals(name)){
            return "运行时异常";
        }else if("bbb".equals(name)){
            return "检查异常";
        }else{
            return "error, " + name;
        }
    }

}
